﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HHMMS.WorkFlow;
using HHMMS.Core.Model;
using HHMMS.Core.Service;
using Bingosoft.Web.Utils;

namespace HHMMS.UI.Modules.Workflow.Forms
{
    public partial class PartsDiscard : WFUserControl
    {
        private readonly PartsDiscardService discardService = ObjectHelper.GetObject<PartsDiscardService>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.ActionType > 0)
            {
                var discardRecord = discardService.GetPartsDiscardRecord(this.DataKey.ConvertTo<int>());
                if (discardRecord != null)
                {
                    SmartForm.Fill(this, discardRecord);
                }
            }
        }

        public override bool SaveData()
        {
            var discardRecord = SmartForm.GetEntity<PartsDiscardRecord>(this);

            discardService.SaveOrUpdatePartsDiscardRecord(discardRecord);

            this.Title = discardRecord.Title;
            this.DataKey = discardRecord.Id + "";

            return base.SaveData();
        }

        public override void OnWorkflowExecute(object sender, WorkflowEventArgs e)
        {
            base.OnWorkflowExecute(sender, e);

            var discardRecord = discardService.GetPartsDiscardRecord(this.DataKey.ConvertTo<int>());

            if (discardRecord != null)
            {
                discardRecord.WFInstanceId = e.Instance.InstanceId;
                discardRecord.Status = e.Instance.InstanceStatus + 1;
                if (e.Instance.InstanceStatus == 2)
                {
                    discardRecord.ApprovalTime = DateTime.Now;
                    discardRecord.ApprovalUserId = Bingosoft.Security.SecurityContext.User.Id;
                }
                discardService.SaveOrUpdatePartsDiscardRecord(discardRecord);
            }
        }
    }
}